import React, { Component } from 'react';
import { Table, Modal, Button, Row, Col, Radio } from 'antd';
// import Swiper from 'swiper';
// import 'swiper/swiper-bundle.css';
import api from '../../api/api';
import './HealthyTable.scss';
import SwiperCore, { Navigation, Thumbs } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
import CustomerCart from '../customerCenter/CustomerCard';
import 'swiper/swiper.scss';
import 'swiper/components/navigation/navigation.scss';
import HasPermission, { testPermission } from '../common/HasPermission';
SwiperCore.use([Navigation, Thumbs]);

class HealthyTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableData: {},
      statusVisible: false,
      currentRow: {},
      currentImg: null,
      currentImgIndex: 0,
      currentImgStyle: {
        scale: 1,
        rotate: 0,
      },
      loading: false,
      status: '',
      thumbsSwiper: null,
      gallerySwiper: null,
      pageSize: props.limit,
      currentPage: 1,
      status: ''
    };
  }
  componentWillMount() {
    this.setState({
      tableData: this.props.tableData,
    });
  }
  componentDidMount() { }
  componentDidUpdate() { }
  componentWillReceiveProps(nextProps) {
    if (
      JSON.stringify(this.props.tableData) !==
      JSON.stringify(nextProps.tableData)
    ) {
      this.setState({
        tableData: nextProps.tableData,
      });
    }
    if (nextProps.currentPage !== this.state.currentPage) {
      this.setState({
        currentPage: nextProps.currentPage
      })
    }
  }

  // 审核
  verifyStatus = (row) => () => {
    this.setState(
      {
        currentRow: row,
      },
      () => {
        this.setState({
          statusVisible: true,
        });
        if (this.state.gallerySwiper) {
          this.state.gallerySwiper.slideTo(0)
          this.state.thumbsSwiper.slideTo(0)
          this.state.gallerySwiper.updateSlides()
          this.state.thumbsSwiper.updateSlides()
          this.state.gallerySwiper.update()
          this.state.thumbsSwiper.update()
        }
      }
    );
  };
  changeCurrentRowStatus = (event) => {
    this.setState({
      status: event.target.value,
    });
  };
  statusSubmit = async (row) => {
    if (this.state.status === '') {
      Modal.warning({
        content: '请选择审核结果',
      });
      return
    }
    try {
      let result = await api.checkMemberStatus(
        this.state.currentRow.id,
        this.state.status
      );
      this.setState({
        statusVisible: false,
        status: ''
      });
      this.props.searchData();
    } catch (e) {
      Modal.error({
        content: '审核失败'
      })
    }
  };
  statusSubmitNext = async () => {
    if (this.state.status === '') {
      Modal.warning({
        content: '请选择审核结果',
      });
      return
    }
    try {
      let result = await api.checkMemberStatus(
        this.state.currentRow.id,
        this.state.status
      );
      if (result) {
        let nextId = result.id;

        if (nextId !== null || nextId !== undefined) {
          // let row = this.state.tableData.list.find((item) => {
          //   return item.id === nextId;
          // });
          this.setState({
            currentRow: result,
            status: ''
          });

        } else {
          this.setState({
            statusVisible: false,
            status: ''
          });
          this.props.searchData();
          Modal.success({
            content: '无待审批任务',
          });

        }
      } else {
        this.setState({
          statusVisible: false,
          status: ''
        });
        this.props.searchData();
        Modal.success({
          content: '无待审批任务',
        });
      }
    } catch (e) {
      this.setState({
        statusVisible: false,
        status: ''
      });
      this.props.searchData();
      Modal.success({
        content: '无待审批任务',
      });
    }
  };
  modalClose = () => {
    // this.state.gallerySwiper.destroy();
    this.setState({
      statusVisible: false,
    });
    this.props.searchData();
  };
  setGallerySwiper = (gallerySwiper) => {
    // console.log('gallerySwiper:', gallerySwiper);
    this.setState({
      gallerySwiper,
    });
  };

  setThumbsSwiper = (thumbsSwiper) => {
    // console.log('thumbsSwiper:', thumbsSwiper);
    this.setState({
      thumbsSwiper,
    });
  };

  tableChange = (pagination) => {
    this.props.pageChange(pagination)
  };
  zoomOutImg = () => {
    // let scale = this.state.currentImgStyle.scale
    let { scale } = this.state.currentImgStyle
    scale += 1;
    let newObj = Object.assign({}, this.state.currentImgStyle, {
      scale: scale,
    })
    this.setState({
      currentImgStyle: newObj
    })
  }
  zoomInImg = () => {
    let { scale } = this.state.currentImgStyle
    if (scale > 1) {
      scale -= 1
    }
    let newObj = Object.assign({}, this.state.currentImgStyle, {
      scale: scale,
    })
    this.setState({
      currentImgStyle: newObj
    })

  }
  redoImg = () => {
    let { rotate } = this.state.currentImgStyle
    rotate += 90
    let newObj = Object.assign({}, this.state.currentImgStyle, {
      rotate: rotate,
    })
    this.setState({
      currentImgStyle: newObj
    })
  }
  undoImg = () => {
    let { rotate } = this.state.currentImgStyle
    rotate -= 90
    let newObj = Object.assign({}, this.state.currentImgStyle, {
      rotate: rotate,
    })

    this.setState({
      currentImgStyle: newObj
    })
  }
  recoverImg = () => {
    this.setState({
      currentImgStyle: {
        scale: 1,
        rotate: 0,
      },
    })
    this.refs.currentImg.style.left = '0px'
    this.refs.currentImg.style.top = '0px'
  }
  thumbsSlideChange = (swiper) => {
    this.setState({
      currentImgStyle: {
        scale: 1,
        rotate: 0
      }
    })
    this.setState({
      currentImgIndex: swiper.activeIndex
    })
    this.refs.currentImg.style.left = '0px'
    this.refs.currentImg.style.top = '0px'

  }
  moveImg = (event) => {
    event.persist()
    event.preventDefault()
    event.stopPropagation()
    let diffX = event.pageX
    let diffY = event.pageY

    let target = null
    let targetLeft = 0
    let targetTop = 0
    if (event.target.nodeName.toUpperCase() === 'IMG') {
      target = event.target
      targetLeft = parseInt(window.getComputedStyle(target).left)
      targetTop = parseInt(window.getComputedStyle(target).top)
    }

    document.onmousemove = (event) => {

      event.preventDefault()
      event.stopPropagation()
      if (target) {

        let tempLeft = targetLeft + event.pageX - diffX
        let tempTop = targetTop + event.pageY - diffY
        let scale = this.state.currentImgStyle.scale


        // 图片容器的宽和高是 860 450 ,
        let borderLeft = 860 + 430 * (scale - 1)
        let borderTop = 450 + 225 * (scale - 1)


        // 边界加20px，省的把图片拖出去了
        if ((-borderLeft + 20) < tempLeft && tempLeft < (borderLeft - 20) && (-borderTop + 20) < tempTop && tempTop < (borderTop - 20)) {
          target.style.left = tempLeft + 'px'
          target.style.top = tempTop + 'px'
        }

      }
    }
    document.onmouseup = (event) => {
      document.onmousemove = null
      document.onmousedown = null
    }
  }
  // 显示会员卡片
  showCustomerCard = (id) => {
    // console.log('showCustomerCard id:', id);
    this.setState({
      customerCardVisible: true,
      currentCustomerId: id,
    });
  };
  hideCustomerCard = () => {
    this.setState({
      customerCardVisible: false,
    });
  };


  render() {
    const columns = [
      {
        title: '会员姓名',
        dataIndex: 'name',
        width: 150,
        key: 'name',
        render: (text, row) => {
          return (
            <span
              style={{ textDecoration: 'underline', cursor: 'pointer' }}
              onClick={() => {
                this.showCustomerCard(row.patientId);
              }}
            >
              {text}
            </span>
          );
        },
      },
      // {
      //   title: '身份证号',
      //   dataIndex: 'idCard',
      //   width: 150,
      //   key: 'idCard',
      // },
      {
        title: '购药时间',
        dataIndex: 'purchaseDate',
        key: 'purchaseDate',
      },
      {
        title: '上传时间',
        dataIndex: 'uploadDate',
        key: 'uploadDate',
      },
      {
        title: '审核状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, row) => {
          let newText = '';
          switch (text) {
            case 0:
              newText = '未审核';
              break;
            case 10:
              newText = '通过';
              break;
            case 20:
              newText = '未通过';
              break;
            default:
              newText = '';
          }
          return newText;
        },
      },
      {
        title: '审核时间',
        dataIndex: 'checkDate',
        key: 'checkDate',
      },
      {
        title: '操作',
        key: 'operation',
        render: (text, row) => {
          if (row.status === 0) {
            // 未审核
            return (
              <HasPermission match="health.medicinerecord.audit">
                <span
                  style={{ textDecoration: 'underline', cursor: 'pointer' }}
                  onClick={this.verifyStatus(row)}
                >
                  审核
                </span>
              </HasPermission>
            );
          } else {
            return <span></span>;
          }
        },
      },
    ];
    let swiperSlideList = [];
    if (Array.isArray(this.state.currentRow.pics)) {
      swiperSlideList = this.state.currentRow.pics.map((item, index) => {
        return (
          <SwiperSlide key={index}>
            <img src={item} />
          </SwiperSlide>
        );
      });
    }

    let currentRow = this.state.currentRow;
    let currentImgSrc = ''
    if (Array.isArray(currentRow.pics)) {
      currentImgSrc = currentRow.pics[this.state.currentImgIndex]
    }
    let currentImgStyle = this.state.currentImgStyle
    // 分页
    let { tableData } = this.state;

    let data = tableData
    return (
      <div className='table-box block'>
        <CustomerCart
          id={this.state.currentCustomerId}
          visible={this.state.customerCardVisible}
          hideCustomerCard={this.hideCustomerCard}
        ></CustomerCart>
        <Table
          columns={columns}
          dataSource={data.list}
          rowKey={(record) => record.id}
          pagination={{
            showSizeChanger: true,
            total: data.pageIndex !== 1 && data.count === data.pageSize ? data.count + 1 : data.count,
            showTotal: () => `第 ${data.pageIndex} 页`,
            pageSizeOptions: ['10', '20', '50', '100'],
            current: data.pageIndex,
            pageSize: data.pageSize,
          }}
          onChange={this.tableChange}
        />
        <Modal
          title='购药记录审核'
          visible={this.state.statusVisible}
          onCancel={this.modalClose}
          className='statusModal'
          maskClosable={false}
          width={1000}
          footer={[
            <Button
              key='submit'
              size='large'
              onClick={this.statusSubmit}
              loading={this.loading}
            >
              提交
            </Button>,
            <Button
              key='submitNext'
              type='primary'
              size='large'
              loading={this.loading}
              onClick={this.statusSubmitNext}
            >
              提交并下一个
            </Button>,
          ]}
        >
          {/* <Swiper
            spaceBetween={50}
            slidesPerView={1}
            thumbs={{ swiper: this.state.thumbsSwiper }}
            onSwiper={this.setGallerySwiper}
            className='gallery-top'
            navigation
          >
            {swiperSlideList}
          </Swiper> */}
          <div className='gallery'>
            <img src={currentImgSrc} alt="" ref='currentImg' style={{ transform: `scale(${currentImgStyle.scale}) rotate(${currentImgStyle.rotate}deg)` }} draggable onMouseDown={this.moveImg} />
            <div className='img-tools'>
              <div className="tool zoom-out" onClick={this.zoomOutImg} title='放大'>
                <svg t="1599031160433" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8026" width="200" height="200"><path d="M637 443H519V309c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v134H325c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h118v134c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V519h118c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z" p-id="8027"></path><path d="M921 867L775 721c122.1-148.9 113.6-369.5-26-509-148-148.1-388.4-148.1-537 0-148.1 148.6-148.1 389 0 537 139.5 139.6 360.1 148.1 509 26l146 146c3.2 2.8 8.3 2.8 11 0l43-43c2.8-2.7 2.8-7.8 0-11zM696 696c-118.8 118.7-311.2 118.7-430 0-118.7-118.8-118.7-311.2 0-430 118.8-118.7 311.2-118.7 430 0 118.7 118.8 118.7 311.2 0 430z" p-id="8028"></path></svg>
              </div>
              <div className="tool zoom-in" onClick={this.zoomInImg} title='缩小'>
                <svg t="1599031178703" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8157" width="200" height="200"><path d="M637 443H325c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h312c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z" p-id="8158"></path><path d="M921 867L775 721c122.1-148.9 113.6-369.5-26-509-148-148.1-388.4-148.1-537 0-148.1 148.6-148.1 389 0 537 139.5 139.6 360.1 148.1 509 26l146 146c3.2 2.8 8.3 2.8 11 0l43-43c2.8-2.7 2.8-7.8 0-11zM696 696c-118.8 118.7-311.2 118.7-430 0-118.7-118.8-118.7-311.2 0-430 118.8-118.7 311.2-118.7 430 0 118.7 118.8 118.7 311.2 0 430z" p-id="8159"></path></svg>
              </div>
              <div className="tool redo" onClick={this.redoImg} title='左旋'>
                <svg t="1599031200030" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8288" width="200" height="200"><path d="M758.2 839.1C851.8 765.9 912 651.9 912 523.9 912 303 733.5 124.3 512.6 124 291.4 123.7 112 302.8 112 523.9c0 125.2 57.5 236.9 147.6 310.2 3.5 2.8 8.6 2.2 11.4-1.3l39.4-50.5c2.7-3.4 2.1-8.3-1.2-11.1-8.1-6.6-15.9-13.7-23.4-21.2-29.4-29.4-52.5-63.6-68.6-101.7C200.4 609 192 567.1 192 523.9s8.4-85.1 25.1-124.5c16.1-38.1 39.2-72.3 68.6-101.7 29.4-29.4 63.6-52.5 101.7-68.6C426.9 212.4 468.8 204 512 204s85.1 8.4 124.5 25.1c38.1 16.1 72.3 39.2 101.7 68.6 29.4 29.4 52.5 63.6 68.6 101.7 16.7 39.4 25.1 81.3 25.1 124.5s-8.4 85.1-25.1 124.5c-16.1 38.1-39.2 72.3-68.6 101.7-9.3 9.3-19.1 18-29.3 26L668.2 724c-4.1-5.3-12.5-3.5-14.1 3l-39.6 162.2c-1.2 5 2.6 9.9 7.7 9.9l167 0.8c6.7 0 10.5-7.7 6.3-12.9l-37.3-47.9z" p-id="8289"></path></svg>
              </div>
              <div className="tool undo" onClick={this.undoImg} title='右旋'>
                <svg t="1599031217260" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8418" width="200" height="200"><path d="M511.4 124C290.5 124.3 112 303 112 523.9c0 128 60.2 242 153.8 315.2l-37.5 48c-4.1 5.3-0.3 13 6.3 12.9l167-0.8c5.2 0 9-4.9 7.7-9.9L369.8 727c-1.6-6.5-10-8.3-14.1-3L315 776.1c-10.2-8-20-16.7-29.3-26-29.4-29.4-52.5-63.6-68.6-101.7C200.4 609 192 567.1 192 523.9s8.4-85.1 25.1-124.5c16.1-38.1 39.2-72.3 68.6-101.7 29.4-29.4 63.6-52.5 101.7-68.6C426.9 212.4 468.8 204 512 204s85.1 8.4 124.5 25.1c38.1 16.1 72.3 39.2 101.7 68.6 29.4 29.4 52.5 63.6 68.6 101.7 16.7 39.4 25.1 81.3 25.1 124.5s-8.4 85.1-25.1 124.5c-16.1 38.1-39.2 72.3-68.6 101.7-7.5 7.5-15.3 14.5-23.4 21.2-3.4 2.8-3.9 7.7-1.2 11.1l39.4 50.5c2.8 3.5 7.9 4.1 11.4 1.3C854.5 760.8 912 649.1 912 523.9c0-221.1-179.4-400.2-400.6-399.9z" p-id="8419"></path></svg>
              </div>
              <div className='tool recover' onClick={this.recoverImg} title='恢复'>
                <svg t="1599103729058" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8026" width="200" height="200"><path d="M168 504.2c1-43.7 10-86.1 26.9-126 17.3-41 42.1-77.7 73.7-109.4S337 212.3 378 195c42.4-17.9 87.4-27 133.9-27s91.5 9.1 133.8 27c40.9 17.3 77.7 42.1 109.3 73.8 9.9 9.9 19.2 20.4 27.8 31.4l-60.2 47c-5.3 4.1-3.5 12.5 3 14.1l175.7 43c5 1.2 9.9-2.6 9.9-7.7l0.8-180.9c0-6.7-7.7-10.5-12.9-6.3l-56.4 44.1C765.8 155.1 646.2 92 511.8 92 282.7 92 96.3 275.6 92 503.8c-0.1 4.5 3.5 8.2 8 8.2h60c4.4 0 7.9-3.5 8-7.8zM924 512h-60c-4.4 0-7.9 3.5-8 7.8-1 43.7-10 86.1-26.9 126-17.3 41-42.1 77.8-73.7 109.4S687 811.7 646 829c-42.4 17.9-87.4 27-133.9 27s-91.5-9.1-133.9-27c-40.9-17.3-77.7-42.1-109.3-73.8-9.9-9.9-19.2-20.4-27.8-31.4l60.2-47c5.3-4.1 3.5-12.5-3-14.1l-175.7-43c-5-1.2-9.9 2.6-9.9 7.7l-0.7 181c0 6.7 7.7 10.5 12.9 6.3l56.4-44.1C258.2 868.9 377.8 932 512.2 932c229.2 0 415.5-183.7 419.8-411.8 0.1-4.5-3.5-8.2-8-8.2z" p-id="8027"></path></svg>
              </div>
            </div>
          </div>

          <Swiper
            spaceBetween={50}
            slidesPerView={4}
            centeredSlides={true}
            onSwiper={this.setThumbsSwiper}
            onSlideChange={this.thumbsSlideChange}
            className='gallery-thumbs'
            navigation
          >
            {swiperSlideList}
          </Swiper>

          {/* 会员信息 */}
          <div className='info'>
            <Row>
              <Col span={4}>会员姓名：</Col>
              <Col span={8}>{currentRow.name}</Col>
              {/* <Col span={4}>身份证号</Col>
              <Col span={8}>{currentRow.idCard}</Col> */}
            </Row>
            <Row>
              <Col span={4}>审核结果</Col>
              <Col span={8}>
                <Radio.Group onChange={this.changeCurrentRowStatus} value={this.state.status}>
                  <Radio value={10}>
                    通过
                  </Radio>
                  <Radio value={20}>不通过</Radio>
                </Radio.Group>
              </Col>
            </Row>
          </div>
        </Modal>
      </div>
    );
  }
}

export default HealthyTable;
